package com.health.viewscontrols;

import java.util.HashMap;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONObject;

import com.google.gson.Gson;
import com.health.ConfigActivity;
import com.health.NovaActivity;
import com.health.NovaApplication;
import com.health.R;
import com.health.model.UpdateOriginInfoBean;
import com.health.tablebean.BD_DD_AREA;
import com.health.tablebean.BD_ORGANIZE_EMPLOYEE;
import com.health.tablebean.BD_ORGANIZE_INSTITUTION;
import com.health.tools.GlobalConts;
import com.health.tools.SPUtil;
import com.health.tools.WebService;
import com.health.webservices.WebServiceConts;
import com.novabluetooth.services.ktxyj.Constants;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.LinearInterpolator;
import android.view.animation.RotateAnimation;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import static com.novabluetooth.services.ktxyj.Constants.AREA_CODE;

/**
 * 下载数据界面
 */

public class HomeDataDownloadActivity extends NovaActivity implements OnClickListener {

    protected static final int MSG1_1 = 0;
    private static final int MSG1_2 = 1;
    private static final int MSG2_1 = 2;
    protected static final int MSG2_2 = 3;
    protected static final int MSG3_1 = 4;
    protected static final int MSG3_2 = 5;
    protected static final int MSG_DOWNLOAD_AREA = 6;
    protected static final int MSG_DOWNLOAD_ORGANIZE = 7;
    protected static final int MSG_DOWNLOAD_EMPLOYEE = 8;
    private ProgressBar pb1;
    private ProgressBar pb2;
    private ProgressBar pb3;
    private ProgressBar pb4;
    private ProgressBar pb1_fail;
    private ProgressBar pb2_fail;
    private ProgressBar pb3_fail;
    private ProgressBar pb1_success;
    private ProgressBar pb2_success;
    private ProgressBar pb3_success;
    private ImageView iv_1_1;// 下载失败
    private ImageView iv_1_2;// 下载中
    private ImageView iv_1_3;// 已下载
    private ImageView iv_2_1;
    private ImageView iv_2_2;
    private ImageView iv_2_3;
    private ImageView iv_3_1;
    private ImageView iv_3_2;
    private ImageView iv_3_3;
    private ImageView iv_4_1;
    private ImageView iv_4_2;
    private ImageView iv_4_3;
    private TextView tv_1_1;// 下载失败
    private TextView tv_1_2;// 下载中
    private TextView tv_1_3;// 已下载
    private TextView tv_2_1;
    private TextView tv_2_2;
    private TextView tv_2_3;
    private TextView tv_3_1;
    private TextView tv_3_2;
    private TextView tv_3_3;
    private TextView tv_4_1;
    private TextView tv_4_2;
    private TextView tv_4_3;
    private LinearLayout ll_3;// 医生信息
    private LinearLayout ll_4;// 签约信息
    private Button bt_download;// 下载
    private Button bt_enter;// 登录
    private int pro = 0;
    private int institutionCount = 0;
    private int areaCount = 0;
    private int employeeCount = 0;
    private String areaData;
    private String institutionData;
    private String employeeData;
    private boolean hasExtra;// 是否是从设置界面跳转
    private LinearLayout ll_tishi;
    private TextView tv_version;


    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            // 处理消息
            switch (msg.what) {
                case MSG_DOWNLOAD_AREA:
                    try {
                        WebService webService = new WebService(mContext) {
                            @Override
                            public void start(String message) {
                                super.start(message);// 开始 46fas
                                System.out.println("start::" + message);
                                Log.e("start-------", message);
                            }

                            @Override
                            public void complete(String message) {
                                super.complete(message);
                                System.out.println("complete::" + message);
                                areaData = message;
                                Log.e("返回数据-------", message);
                                if (areaData != null) {
                                    analysis_areadata(areaData);
                                } else {
                                    Message msg = new Message();
                                    msg.what = MSG1_2;
                                    mHandler.sendMessage(msg);
                                }

                            }

                            public void onError(String message) {
                                Log.e("tag", message);
                                Message msg1 = new Message();
                                msg1.what = MSG1_2;
                                mHandler.sendMessage(msg1);
                            }

                            ;
                        };
                        HashMap<String, Object> params = new HashMap<String, Object>();
//					 params.put("gbCode", NovaApplication.getXzqhNo());
                        params.put("gbCode", SPUtil.getRegisterZCMAll(mContext));
                        System.out.println("地址" + GlobalConts.getUrlPost() + WebServiceConts.WEBSERVICE_URL_XZQ
                                + SPUtil.getRegisterZCMAll(mContext));
                        // webService.downloaddata(GlobalConts.getUrlPost() +
                        // WebServiceConts.WEBSERVICE_URL_XZQ,
                        // WebServiceConts.WEBSERVICE_URL_XZQ_METHODNAME,
                        // WebServiceConts.WEBSERVICE_URL_XZQ_NAMESPACE,
                        // null, params, "organize");
                        webService.downloaddata(GlobalConts.getUrlPost() + "?orgDistrictId=380101&mid=4A5F634346A82B95&t=20181216211801",
                                WebServiceConts.WEBSERVICE_URL_XZQ_METHODNAME, WebServiceConts.WEBSERVICE_URL_XZQ_NAMESPACE,
                                null, params, "getBdDdAreaByOrgnazi");//   getBdDdArea
/*
                    webService.downloaddata(GlobalConts.getUrlPost() + WebServiceConts.WEBSERVICE_URL_XZQ,
							WebServiceConts.WEBSERVICE_URL_XZQ_METHODNAME, WebServiceConts.WEBSERVICE_URL_XZQ_NAMESPACE,
							null, params, "getBdDdAreaByOrgnazi");//   getBdDdArea
*/

                    } catch (Exception e) {
                        Message msg1 = new Message();
                        msg1.what = MSG1_2;
                        mHandler.sendMessage(msg1);
                    }

                    break;

                case MSG_DOWNLOAD_ORGANIZE:
                    try {
                        WebService webService = new WebService(mContext) {
                            @Override
                            public void start(String message) {
                                super.start(message);// 开始 46fas
                                System.out.println("start::" + message);
                                Log.e("start-------", message);
                            }

                            @Override
                            public void complete(String message) {
                                super.complete(message);
                                System.out.println("complete::" + message);
                                Log.e("返回数据-------", message);
                                institutionData = message;
                                if (institutionData != null) {
                                    analysis_institutionData(institutionData);
                                } else {
                                    Message msg = new Message();
                                    msg.what = MSG2_2;
                                    mHandler.sendMessage(msg);
                                }

                            }

                            @Override
                            public void onError(String message) {
                                Message msg1 = new Message();
                                msg1.what = MSG2_2;
                                mHandler.sendMessage(msg1);
                            }

                            ;
                        };
                        HashMap<String, Object> params = new HashMap<String, Object>();
//					 params.put("gbCode", NovaApplication.getXzqhNo());
                        params.put("gbCode", SPUtil.getRegisterZCMAll(mContext));
                        webService.downloaddata(GlobalConts.getUrlPost() + WebServiceConts.WEBSERVICE_URL_JG,
                                WebServiceConts.WEBSERVICE_URL_JG_METHODNAME, WebServiceConts.WEBSERVICE_URL_JG_NAMESPACE,
                                null, params, "getBdOrganizeByOrgnazi");//  getBdOrganize
                        // webService.downloaddata("370188","getBdOrganize");
                    } catch (Exception e) {
                        Message msg1 = new Message();
                        msg1.what = MSG2_2;
                        mHandler.sendMessage(msg1);
                    }

                    break;

                case MSG_DOWNLOAD_EMPLOYEE:
                    try {
                        WebService webService = new WebService(mContext) {
                            @Override
                            public void start(String message) {
                                super.start(message);// 开始 46fas
                                System.out.println("start::" + message);
                                Log.e("start-------", message);
                            }

                            @Override
                            public void complete(String message) {
                                super.complete(message);
                                System.out.println("complete::" + message);
                                Log.e("返回数据-------", message);
                                employeeData = message;
                                if (employeeData != null) {
                                    analysis_employeeData(employeeData);
                                } else {
                                    Message msg = new Message();
                                    msg.what = MSG3_2;
                                    mHandler.sendMessage(msg);
                                }

                            }

                            @Override
                            public void onError(String message) {
                                Message msg1 = new Message();
                                msg1.what = MSG3_2;
                                mHandler.sendMessage(msg1);
                            }

                        };
                        HashMap<String, Object> params = new HashMap<String, Object>();
                        // params.put("organcode", "370188");
                        params.put("organcode", SPUtil.getRegisterZCMAll(mContext));
//					 params.put("organcode", NovaApplication.getXzqhNo());
                        webService.downloaddata(GlobalConts.getUrlPost() + WebServiceConts.WEBSERVICE_URL_EMPLOYEE,
                                WebServiceConts.WEBSERVICE_URL_EMPLOYEE_METHODNAME,
                                WebServiceConts.WEBSERVICE_URL_EMPLOYEE_NAMESPACE, null, params, "getBdOrganizeEmployeeByOrgnazi");//  getBdOrganizeEmployee
                        // webService.downloaddata("370188","getBdOrganize");
                    } catch (Exception e) {
                        Message msg1 = new Message();
                        msg1.what = MSG3_2;
                        mHandler.sendMessage(msg1);
                    }

                    break;
                case MSG1_1:
                    // 设置滚动条值
                    pb1.setProgress(pro);
                    if (pro == 100) {
                        // 行政区划下载成功
                        iv_1_3.setVisibility(View.VISIBLE);
                        tv_1_3.setVisibility(View.VISIBLE);

                        iv_1_1.setVisibility(View.GONE);
                        tv_1_1.setVisibility(View.GONE);

                        stopRotate(iv_1_2);
                        tv_1_2.setVisibility(View.GONE);

//                        new Thread(run2).start();
                    }
                    break;
                case MSG1_2:
                    // 行政区划下载失败
                    iv_1_2.setVisibility(View.GONE);
                    tv_1_2.setVisibility(View.GONE);

                    iv_1_1.setVisibility(View.VISIBLE);
                    tv_1_1.setVisibility(View.VISIBLE);

                    iv_1_3.setVisibility(View.GONE);
                    tv_1_3.setVisibility(View.GONE);

                    pb1.setVisibility(View.GONE);
                    pb1_fail.setVisibility(View.VISIBLE);

                    iv_2_1.setVisibility(View.VISIBLE);
                    tv_2_1.setVisibility(View.VISIBLE);
                    pb2.setVisibility(View.GONE);
                    pb2_fail.setVisibility(View.VISIBLE);
                    iv_3_1.setVisibility(View.VISIBLE);
                    tv_3_1.setVisibility(View.VISIBLE);
                    pb3.setVisibility(View.GONE);
                    pb3_fail.setVisibility(View.VISIBLE);
                    bt_download.setClickable(true);
                    break;
                case MSG2_1:
                    // 设置滚动条值
                    pb2.setProgress(pro);
                    if (pro == 100) {
                        // 机构信息下载成功
                        iv_2_3.setVisibility(View.VISIBLE);
                        tv_2_3.setVisibility(View.VISIBLE);

                        iv_2_1.setVisibility(View.GONE);
                        tv_2_1.setVisibility(View.GONE);

                        stopRotate(iv_2_2);
                        tv_2_2.setVisibility(View.GONE);
//                        new Thread(run3).start();
                    }
                    break;

                case MSG2_2:
                    // 机构信息下载失败
                    iv_2_2.setVisibility(View.GONE);
                    tv_2_2.setVisibility(View.GONE);

                    iv_2_1.setVisibility(View.VISIBLE);
                    tv_2_1.setVisibility(View.VISIBLE);

                    iv_2_3.setVisibility(View.GONE);
                    tv_2_3.setVisibility(View.GONE);

                    pb2.setVisibility(View.GONE);
                    pb2_fail.setVisibility(View.VISIBLE);

                    iv_3_2.setVisibility(View.GONE);
                    tv_3_2.setVisibility(View.GONE);
                    iv_3_3.setVisibility(View.GONE);
                    tv_3_3.setVisibility(View.GONE);
                    iv_3_1.setVisibility(View.VISIBLE);
                    tv_3_1.setVisibility(View.VISIBLE);

                    pb3.setVisibility(View.GONE);
                    pb3_fail.setVisibility(View.VISIBLE);
                    bt_download.setClickable(true);
                    break;

                case MSG3_1:
                    // 设置滚动条值
                    pb3.setProgress(pro);
                    if (pro == 100) {
                        // 机构信息下载成功
                        iv_3_3.setVisibility(View.VISIBLE);
                        tv_3_3.setVisibility(View.VISIBLE);

                        iv_3_1.setVisibility(View.GONE);
                        tv_3_1.setVisibility(View.GONE);

                        stopRotate(iv_3_2);
                        tv_3_2.setVisibility(View.GONE);

                        Toast.makeText(mContext,"请重新启动系统！",Toast.LENGTH_LONG).show();
                        if (hasExtra) {
                            new AlertDialog.Builder(HomeDataDownloadActivity.this).setTitle("提示").setMessage("下载成功,是否关闭？")
                                    .setPositiveButton("是", new DialogInterface.OnClickListener() {

                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            finish();
                                        }
                                    }).show();
                        }
                    }
                    break;

                case MSG3_2:
                    // 机构信息下载失败
                    iv_3_2.setVisibility(View.GONE);
                    tv_3_2.setVisibility(View.GONE);

                    iv_3_1.setVisibility(View.VISIBLE);
                    tv_3_1.setVisibility(View.VISIBLE);

                    iv_3_3.setVisibility(View.GONE);
                    tv_3_3.setVisibility(View.GONE);

                    pb3.setVisibility(View.GONE);
                    pb3_fail.setVisibility(View.VISIBLE);
                    bt_download.setClickable(true);
                    break;
                default:
                    break;
            }
        }

    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home_data_download);
        hasExtra = getIntent().hasExtra("setting");

        findViews();
        if (hasExtra) {
            ll_tishi.setVisibility(View.GONE);
            bt_enter.setVisibility(View.GONE);
        }
        setListeners();
        setdata();
    }

    @Override
    public void findViews() {
        pb1 = (ProgressBar) findViewById(R.id.pb1);
        pb1_fail = (ProgressBar) findViewById(R.id.pb1_fail);
        pb1_success = (ProgressBar) findViewById(R.id.pb1_success);
        pb2 = (ProgressBar) findViewById(R.id.pb2);
        pb2_fail = (ProgressBar) findViewById(R.id.pb2_fail);
        pb2_success = (ProgressBar) findViewById(R.id.pb2_success);
        pb3_fail = (ProgressBar) findViewById(R.id.pb3_fail);
        pb3_success = (ProgressBar) findViewById(R.id.pb3_success);
        pb3 = (ProgressBar) findViewById(R.id.pb3);
        pb4 = (ProgressBar) findViewById(R.id.pb4);

        iv_1_1 = (ImageView) findViewById(R.id.iv_1_1);
        iv_1_2 = (ImageView) findViewById(R.id.iv_1_2);
        iv_1_3 = (ImageView) findViewById(R.id.iv_1_3);

        iv_2_1 = (ImageView) findViewById(R.id.iv_2_1);
        iv_2_2 = (ImageView) findViewById(R.id.iv_2_2);
        iv_2_3 = (ImageView) findViewById(R.id.iv_2_3);

        iv_3_1 = (ImageView) findViewById(R.id.iv_3_1);
        iv_3_2 = (ImageView) findViewById(R.id.iv_3_2);
        iv_3_3 = (ImageView) findViewById(R.id.iv_3_3);

        iv_4_1 = (ImageView) findViewById(R.id.iv_4_1);
        iv_4_2 = (ImageView) findViewById(R.id.iv_4_2);
        iv_4_3 = (ImageView) findViewById(R.id.iv_4_3);

        tv_1_1 = (TextView) findViewById(R.id.tv_1_1);
        tv_1_2 = (TextView) findViewById(R.id.tv_1_2);
        tv_1_3 = (TextView) findViewById(R.id.tv_1_3);

        tv_2_1 = (TextView) findViewById(R.id.tv_2_1);
        tv_2_2 = (TextView) findViewById(R.id.tv_2_2);
        tv_2_3 = (TextView) findViewById(R.id.tv_2_3);

        tv_3_1 = (TextView) findViewById(R.id.tv_3_1);
        tv_3_2 = (TextView) findViewById(R.id.tv_3_2);
        tv_3_3 = (TextView) findViewById(R.id.tv_3_3);

        tv_4_1 = (TextView) findViewById(R.id.tv_4_1);
        tv_4_2 = (TextView) findViewById(R.id.tv_4_2);
        tv_4_3 = (TextView) findViewById(R.id.tv_4_3);

        ll_3 = (LinearLayout) findViewById(R.id.ll_3);
        ll_4 = (LinearLayout) findViewById(R.id.ll_4);

        ll_tishi = (LinearLayout) findViewById(R.id.ll_tishi);
        ll_tishi.getBackground().setAlpha(10);
        bt_download = (Button) findViewById(R.id.bt_download);
        bt_enter = (Button) findViewById(R.id.bt_enter);
        tv_version = (TextView) findViewById(R.id.tv_version);
        String versionName = GlobalConts.getVerName(HomeDataDownloadActivity.this);
        if (!TextUtils.isEmpty(versionName)) {
            tv_version.setText("V  " + versionName);
        } else {
            tv_version.setText("");
        }
    }

    @Override
    public void setListeners() {

        bt_download.setOnClickListener(this);
        bt_enter.setOnClickListener(this);
    }

    /**
     * 同步机构信息
     **/
    private void updateOriginInfo() {
        new Thread(new Runnable() {

            @Override
            public void run() {
                //用HttpClient发送请求，分为五步
                //第一步：创建HttpClient对象
                HttpClient httpCient = new DefaultHttpClient();
                //第二步：创建代表请求的对象,参数是访问的服务器地址
                HttpGet httpGet = new HttpGet(GlobalConts.getUrlPost() + "?orgDistrictId=" + Constants.AREA_CODE + "&mid=4A5F634346A82B95&t=20181216211801");

                try {
                    //第三步：执行请求，获取服务器发还的相应对象
                    HttpResponse httpResponse = httpCient.execute(httpGet);
                    //第四步：检查相应的状态是否正常：检查状态码的值是200表示正常
                    if (httpResponse.getStatusLine().getStatusCode() == 200) {
                        //第五步：从相应对象当中取出数据，放到entity当中
                        HttpEntity entity = httpResponse.getEntity();
                        String response = EntityUtils.toString(entity, "utf-8");//将entity当中的数据转换为字符串

                        //在子线程中将Message对象发出去
                        if (response != null) {
                            response = response.toString();
                            if (!response.isEmpty()) {
                                analysis_areadata(response);
                            } else {
                                Message msg = new Message();
                                msg.what = MSG1_2;
                                mHandler.sendMessage(msg);
                            }
                        }
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                    Message msg = new Message();
                    msg.what = MSG1_2;
                    mHandler.sendMessage(msg);
                }

            }
        }).start();

    }

    private void setdata() {
        setProgressBarIndeterminateVisibility(true);
        String xzqhNo = NovaApplication.getXzqhNo();
        List<BD_DD_AREA> areas = NovaApplication.fdbmanger.findAllByWhere(BD_DD_AREA.class,
                "GBCODE like'" + xzqhNo + "%'");
        if (areas.size() > 0) {
            pb1_success.setVisibility(View.VISIBLE);
            pb1.setVisibility(View.GONE);
            iv_1_3.setVisibility(View.VISIBLE);
            tv_1_3.setVisibility(View.VISIBLE);
        } else {
            pb1_success.setVisibility(View.GONE);
            pb1.setVisibility(View.VISIBLE);
            iv_1_3.setVisibility(View.GONE);
            tv_1_3.setVisibility(View.GONE);
        }
        List<BD_ORGANIZE_INSTITUTION> institutions = NovaApplication.fdbmanger
                .findAllByWhere(BD_ORGANIZE_INSTITUTION.class, "GBCODE like'" + xzqhNo + "%'");

        if (institutions.size() > 0) {
            pb2_success.setVisibility(View.VISIBLE);
            pb2.setVisibility(View.GONE);
            iv_2_3.setVisibility(View.VISIBLE);
            tv_2_3.setVisibility(View.VISIBLE);
        } else {
            pb2_success.setVisibility(View.GONE);
            pb2.setVisibility(View.VISIBLE);
            iv_2_3.setVisibility(View.GONE);
            tv_2_3.setVisibility(View.GONE);
        }
        List<BD_ORGANIZE_EMPLOYEE> employees = NovaApplication.fdbmanger.findAllByWhere(BD_ORGANIZE_EMPLOYEE.class,
                "GBCODE like'" + xzqhNo + "%'");
        if (employees.size() > 0) {
            pb3_success.setVisibility(View.VISIBLE);
            pb3.setVisibility(View.GONE);
            iv_3_3.setVisibility(View.VISIBLE);
            tv_3_3.setVisibility(View.VISIBLE);
        } else {
            pb3_success.setVisibility(View.GONE);
            pb3.setVisibility(View.VISIBLE);
            iv_3_3.setVisibility(View.GONE);
            tv_3_3.setVisibility(View.GONE);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.bt_download:
                if (!GlobalConts.isNetworkAvailable(HomeDataDownloadActivity.this)) {
                    showTextDialog("请先检查网络");
                    return;
                }
                bt_download.setClickable(false);
                pb1.setVisibility(View.VISIBLE);
                pb1_fail.setVisibility(View.GONE);
                pb1_success.setVisibility(View.GONE);
                pb2.setVisibility(View.VISIBLE);
                pb2_fail.setVisibility(View.GONE);
                pb2_success.setVisibility(View.GONE);
                pb3.setVisibility(View.VISIBLE);
                pb3_fail.setVisibility(View.GONE);
                pb3_success.setVisibility(View.GONE);
                iv_1_3.setVisibility(View.INVISIBLE);
                iv_2_3.setVisibility(View.INVISIBLE);
                iv_3_3.setVisibility(View.INVISIBLE);
                tv_1_3.setVisibility(View.INVISIBLE);
                tv_2_3.setVisibility(View.INVISIBLE);
                tv_3_3.setVisibility(View.INVISIBLE);
                areaCount = 0;
                institutionCount = 0;
                employeeCount = 0;
                // 点击下载按钮
//			new Thread(run1).start();
                updateOriginInfo();
                break;

            case R.id.bt_enter:
                // 点击进入系统
                NovaApplication.setXzqhNo(AREA_CODE);
                List<BD_DD_AREA> areas = NovaApplication.fdbmanger.findAllByWhere(BD_DD_AREA.class,
                        "GBCODE like'" + NovaApplication.getXzqhNo() + "%'");
                List<BD_ORGANIZE_INSTITUTION> institutions = NovaApplication.fdbmanger
                        .findAllByWhere(BD_ORGANIZE_INSTITUTION.class, "GBCODE like'" + NovaApplication.getXzqhNo() + "%'");

                List<BD_ORGANIZE_EMPLOYEE> employees = NovaApplication.fdbmanger.findAll(BD_ORGANIZE_EMPLOYEE.class,
                        "GBCODE ='" + NovaApplication.getXzqhNo() + "'");
                Log.e("***********", areas.size() + "*" + institutions.size() + "*" + employees.size());
                if (areas.size() > 0 && institutions.size() > 0 && employees.size() > 0) {
                    startActivity(new Intent(getApplication(), ConfigActivity.class));
                    finish();
                } else {
                    showTextDialog("请先下载数据，再进入系统");
                }

                break;

            default:
                break;
        }
    }

    /**
     * 下载行政区划信息
     */
    Runnable run1 = new Runnable() {
        public void run() {
            // areaData = GetAreaData.downLoadData(GetAreaData.area);
            Message msg = new Message();
            msg.what = MSG_DOWNLOAD_AREA;
            mHandler.sendMessage(msg);

        }
    };

    /**
     * 下载机构信息
     */
    Runnable run2 = new Runnable() {
        public void run() {
            Message msg = new Message();
            msg.what = MSG_DOWNLOAD_ORGANIZE;
            mHandler.sendMessage(msg);
        }
    };

    /**
     * 下载医生信息
     */
    Runnable run3 = new Runnable() {
        public void run() {
            Message msg = new Message();
            msg.what = MSG_DOWNLOAD_EMPLOYEE;
            mHandler.sendMessage(msg);
        }
    };

    /**
     * 组织机构医生信息解析
     *
     * @param dataInfo 数据源
     */
    private void analysis_areadata(String dataInfo) {
        Gson gson = new Gson();
        UpdateOriginInfoBean data = gson.fromJson(dataInfo, UpdateOriginInfoBean.class);
        if (null != data) {

            if (null != data.getBd_dd_area() && data.getBd_dd_area().size() > 0) {//行政区信息

                for (UpdateOriginInfoBean.BdDdAreaBean areaBean : data.getBd_dd_area()) {

                    List<BD_DD_AREA> beans = NovaApplication.fdbmanger.findAllByWhere(BD_DD_AREA.class,
                            "GBCODE LIKE '%" + areaBean.getGBCODE() + "%'");
                    if (beans.size() > 0) {
                        NovaApplication.fdbmanger.deleteByWhere(BD_DD_AREA.class,
                                "GBCODE='" + areaBean.getGBCODE() + "'");
                    }

                    BD_DD_AREA area = new BD_DD_AREA();
                    area.setAREAPOPULATION(areaBean.getAREAPOPULATION());
                    area.setDLEVEL(areaBean.getDLEVEL());
                    area.setGBCODE(areaBean.getGBCODE());
                    area.setISCITY(areaBean.getISCITY());
                    area.setLNAME(areaBean.getLNAME());
                    area.setNAME(areaBean.getNAME());
                    NovaApplication.fdbmanger.save(area);
                    areaCount++;
                    runOnUiThread(new Runnable() {
                        public void run() {

                            startRotate(iv_1_2);
                            tv_1_2.setVisibility(View.VISIBLE);

                            iv_1_1.setVisibility(View.GONE);
                            tv_1_1.setVisibility(View.GONE);

                            iv_1_3.setVisibility(View.GONE);
                            tv_1_3.setVisibility(View.GONE);
                        }
                    });
                    pro = 100 * areaCount / data.getBd_dd_area().size();
                    Message msg = new Message();
                    msg.what = MSG1_1;
                    mHandler.sendMessage(msg);
                    SystemClock.sleep(100);
                }
            }
            if (null != data.getBd_organize_employee() && data.getBd_organize_employee().size() > 0) {//组织机构人员信息数据解析
                for (UpdateOriginInfoBean.BdOrganizeEmployeeBean employeeBean : data.getBd_organize_employee()) {
                   /* String userid = arr.getJSONObject(i).getString("USER_ID");
                    List<BD_ORGANIZE_EMPLOYEE> beans = NovaApplication.fdbmanger
                            .findAllByWhere(BD_ORGANIZE_EMPLOYEE.class, "USER_ID='" + userid + "'");
                    if (beans.size() > 0) {
                        NovaApplication.fdbmanger.deleteByWhere(BD_ORGANIZE_EMPLOYEE.class,
                                "USER_ID='" + userid + "'");
                    }*/
                    BD_ORGANIZE_EMPLOYEE employee = new BD_ORGANIZE_EMPLOYEE();
                    employee.setBIRTHDAY(employeeBean.getBIRTHDAY());
                    employee.setBUSINESS(employeeBean.getBUSINESS());
                    employee.setBUSINESS_TEXT(employeeBean.getBUSINESS_TEXT());
                    employee.setCARD_NUM(employeeBean.getCARD_NUM());
                    employee.setDEGREE(employeeBean.getDEGREE());
                    employee.setDEPARTID(employeeBean.getDEPARTID());
                    employee.setEDUCATION(employeeBean.getEDUCATION());
                    employee.setGBCODE(employeeBean.getGBCODE());
                    employee.setGRADUATE_DATE(employeeBean.getGRADUATE_DATE());
                    employee.setHOME_ADDR(employeeBean.getHOME_ADDR());
                    employee.setHOME_TEL(employeeBean.getHOME_TEL());
                    employee.setHOME_ZIP(employeeBean.getHOME_ZIP());
                    employee.setIDCARD(employeeBean.getIDCARD());
                    employee.setINPUT_CODE(employeeBean.getINPUT_CODE());
                    employee.setINVALID(employeeBean.getINVALID());
                    employee.setISADMIN(employeeBean.getISADMIN());
                    employee.setMAIL(employeeBean.getMAIL());
                    employee.setMARRIAGE(employeeBean.getMARRIAGE());
                    employee.setMOBILE(employeeBean.getMOBILE());
                    employee.setNAME(employeeBean.getNAME());
                    employee.setNATIONCODE(employeeBean.getNATIONCODE());
                    employee.setOFFICE_FAX(employeeBean.getOFFICE_FAX());
                    employee.setOFFICE_TEL(employeeBean.getOFFICE_TEL());
                    employee.setORG_WORK_DATE(employeeBean.getORG_WORK_DATE());
                    employee.setORGANCODE(employeeBean.getORGANCODE());
                    employee.setPARTY(employeeBean.getPARTY());
                    employee.setPASSWORD(employeeBean.getPASSWORD());
                    employee.setRES1(employeeBean.getRES1());
                    employee.setRES2(employeeBean.getRES2());
                    employee.setSEX(employeeBean.getSEX());
                    employee.setSPECIALITY_TEXT(employeeBean.getSPECIALITY_TEXT());
                    employee.setSTART_WORK_DATE(employeeBean.getSTART_WORK_DATE());
                    employee.setTECHNICAL(employeeBean.getTECHNICAL());
                    employee.setTECHNICAL_TEXT(employeeBean.getTECHNICAL_TEXT());
                    employee.setTYPE(employeeBean.getTYPE());
                    employee.setUNIVERSITY(employeeBean.getUNIVERSITY());
                    employee.setUSER_ID(employeeBean.getUSER_ID());
                    employee.setUSER_NAME(employeeBean.getUSER_NAME());
                    employee.setWORK(employeeBean.getWORK());
                    employee.setWORK_CARD_ID(employeeBean.getWORK_CARD_ID());
                    NovaApplication.fdbmanger.save(employee);
                    employeeCount++;
                    runOnUiThread(new Runnable() {
                        public void run() {

                            startRotate(iv_3_2);
                            tv_3_2.setVisibility(View.VISIBLE);

                            iv_3_1.setVisibility(View.GONE);
                            tv_3_1.setVisibility(View.GONE);

                            iv_3_3.setVisibility(View.GONE);
                            tv_3_3.setVisibility(View.GONE);
                        }

                    });
                    pro = 100 * employeeCount / data.getBd_organize_employee().size();
                    Message msg = new Message();
                    msg.what = MSG3_1;
                    mHandler.sendMessage(msg);
                    SystemClock.sleep(100);

                }
            }
            if (null != data.getBd_organize_institution() && data.getBd_organize_institution().size() > 0) {//机构数据解析

                for (UpdateOriginInfoBean.BdOrganizeInstitutionBean institutionBean : data.getBd_organize_institution()) {

                    String gbcode = institutionBean.getGBCODE();
                    List<BD_ORGANIZE_INSTITUTION> beans = NovaApplication.fdbmanger.findAllByWhere(
                            BD_ORGANIZE_INSTITUTION.class,
                            "GBCODE LIKE '%" + gbcode + "%'");
                    if (beans.size() > 0) {
                        NovaApplication.fdbmanger.deleteByWhere(BD_ORGANIZE_INSTITUTION.class,
                                "GBCODE LIKE '%" + gbcode + "%'");
                    }

                    BD_ORGANIZE_INSTITUTION institution = new BD_ORGANIZE_INSTITUTION();
                    institution.setADDRESS(institutionBean.getADDRESS());
                    institution.setAREA_CODE(institutionBean.getAREA_CODE());
                    institution.setAREAPOPULATION(institutionBean.getAREAPOPULATION());
                    institution.setARTIFICIAL_IDCARD(institutionBean.getARTIFICIAL_IDCARD());
                    institution.setARTIFICIAL_MOBIL(institutionBean.getARTIFICIAL_MOBIL());
                    institution.setARTIFICIAL_PERSON(institutionBean.getARTIFICIAL_PERSON());
                    institution.setARTIFICIAL_TEL(institutionBean.getARTIFICIAL_TEL());
                    institution.setECONOMYCODE(institutionBean.getECONOMYCODE());
                    institution.setEND_DATE(institutionBean.getEND_DATE());
                    institution.setF_NUMBER(institutionBean.getF_NUMBER());
                    institution.setFAX(institutionBean.getFAX());
                    institution.setFULL_CODE(institutionBean.getFULL_CODE());
                    institution.setGBCODE(institutionBean.getGBCODE());
                    institution.setGENRECODE(institutionBean.getGENRECODE());
                    institution.setGRADECODE(institutionBean.getGRADECODE());
                    institution.setINPUT_CODE(institutionBean.getINPUT_CODE());
                    institution.setINVALID(institutionBean.getINVALID());
                    institution.setM_NUMBER(institutionBean.getM_NUMBER());
                    institution.setMAIL(institutionBean.getMAIL());
                    institution.setMANAGECODE(institutionBean.getMANAGECODE());
                    institution.setOLDORGANNAME(institutionBean.getOLDORGANNAME());
                    institution.setORGANCODE(institutionBean.getORGANCODE());
                    institution.setORGANNAME(institutionBean.getORGANNAME());
                    institution.setORGANSTATION(institutionBean.getORGANSTATION());
                    institution.setPARENTID(institutionBean.getPARENTID());
                    institution.setRES1(institutionBean.getRES1());
                    institution.setRES2(institutionBean.getRES2());
                    institution.setSTART_DATE(institutionBean.getSTART_DATE());
                    institution.setTEL(institutionBean.getTEL());
                    NovaApplication.fdbmanger.save(institution);
                    institutionCount++;
                    runOnUiThread(new Runnable() {
                        public void run() {
                            startRotate(iv_2_2);
                            tv_2_2.setVisibility(View.VISIBLE);

                            iv_2_1.setVisibility(View.GONE);
                            tv_2_1.setVisibility(View.GONE);

                            iv_2_3.setVisibility(View.GONE);
                            tv_2_3.setVisibility(View.GONE);
                        }

                    });
                    pro = 100 * institutionCount / data.getBd_organize_institution().size();
                    Log.e("pro", pro + "00000000000000");
                    Message msg = new Message();
                    msg.what = MSG2_1;
                    mHandler.sendMessage(msg);
                    SystemClock.sleep(100);
                }
            } else {
                Message msg = new Message();
                msg.what = MSG1_2;
                mHandler.sendMessage(msg);
            }
        }

    }

    /**
     * 机构数据解析
     *
     * @param institutionData2
     */
    protected void analysis_institutionData(String institutionData2) {
        JSONObject objs;
        try {
            objs = new JSONObject(institutionData2.toString());
            if (objs.has("success")) {
                if (objs.getBoolean("success")) {
                    if (objs.has("data")) {
                        JSONArray arr = objs.getJSONArray("data");
                        final int length = arr.length();
                        if (length > 0) {
                            Gson gson = new Gson();
                            for (int i = 0; i < length; i++) {
                                String gbcode = arr.getJSONObject(i).getString("GBCODE");
                                String organcode = arr.getJSONObject(i).getString("ORGANCODE");
                                List<BD_ORGANIZE_INSTITUTION> beans = NovaApplication.fdbmanger.findAllByWhere(
                                        BD_ORGANIZE_INSTITUTION.class,
//										"GBCODE LIKE '%" +gbcode+ "%'"+ "AND ORGANCODE LIKE '%" +organcode+ "%'");
                                        "GBCODE LIKE '%" + gbcode + "%'");
                                if (beans.size() > 0) {
                                    NovaApplication.fdbmanger.deleteByWhere(BD_ORGANIZE_INSTITUTION.class,
//											"GBCODE LIKE '%" +gbcode+ "%'" + "AND ORGANCODE LIKE '%" +organcode+ "%'");
                                            "GBCODE LIKE '%" + gbcode + "%'");

                                }
                            }
                            for (int i = 0; i < length; i++) {
                                JSONObject obj = arr.getJSONObject(i);
                                BD_ORGANIZE_INSTITUTION institution = new BD_ORGANIZE_INSTITUTION();
                                institution.setADDRESS(obj.getString("ADDRESS"));
                                institution.setAREA_CODE(obj.getString("AREA_CODE"));
                                institution.setAREAPOPULATION(obj.getString("AREAPOPULATION"));
                                institution.setARTIFICIAL_IDCARD(obj.getString("ARTIFICIAL_IDCARD"));
                                institution.setARTIFICIAL_MOBIL(obj.getString("ARTIFICIAL_MOBIL"));
                                institution.setARTIFICIAL_PERSON(obj.getString("ARTIFICIAL_PERSON"));
                                institution.setARTIFICIAL_TEL(obj.getString("ARTIFICIAL_TEL"));
                                institution.setECONOMYCODE(obj.getString("ECONOMYCODE"));
                                institution.setEND_DATE(obj.getString("END_DATE"));
                                institution.setF_NUMBER(obj.getString("F_NUMBER"));
                                institution.setFAX(obj.getString("FAX"));
                                institution.setFULL_CODE(obj.getString("FULL_CODE"));
                                institution.setGBCODE(obj.getString("GBCODE"));
                                institution.setGENRECODE(obj.getString("GENRECODE"));
                                institution.setGRADECODE(obj.getString("GRADECODE"));
                                institution.setINPUT_CODE(obj.getString("INPUT_CODE"));
                                institution.setINVALID(obj.getString("INVALID"));
                                institution.setM_NUMBER(obj.getString("M_NUMBER"));
                                institution.setMAIL(obj.getString("MAIL"));
                                institution.setMANAGECODE(obj.getString("MANAGECODE"));
                                institution.setOLDORGANNAME(obj.getString("OLDORGANNAME"));
                                institution.setORGANCODE(obj.getString("ORGANCODE"));
                                institution.setORGANNAME(obj.getString("ORGANNAME"));
                                institution.setORGANSTATION(obj.getString("ORGANSTATION"));
                                institution.setPARENTID(obj.getString("PARENTID"));
                                institution.setRES1(obj.getString("RES1"));
                                institution.setRES2(obj.getString("RES2"));
                                institution.setSTART_DATE(obj.getString("START_DATE"));
                                institution.setTEL(obj.getString("TEL"));
                                NovaApplication.fdbmanger.save(institution);
                                institutionCount++;
                                runOnUiThread(new Runnable() {
                                    public void run() {
                                        startRotate(iv_2_2);
                                        tv_2_2.setVisibility(View.VISIBLE);

                                        iv_2_1.setVisibility(View.GONE);
                                        tv_2_1.setVisibility(View.GONE);

                                        iv_2_3.setVisibility(View.GONE);
                                        tv_2_3.setVisibility(View.GONE);
                                    }

                                });
                                pro = 100 * institutionCount / length;
                                Log.e("pro", pro + "00000000000000");
                                Message msg = new Message();
                                msg.what = MSG2_1;
                                mHandler.sendMessage(msg);
                                SystemClock.sleep(100);
                            }
                        }
                    }
                } else {
                    Message msg = new Message();
                    msg.what = MSG2_2;
                    mHandler.sendMessage(msg);

                }
            }
        } catch (Exception e) {
            Message msg = new Message();
            msg.what = MSG2_2;
            mHandler.sendMessage(msg);
        } finally {
            bt_download.setClickable(true);
        }
    }

    /**
     * 组织机构人员信息数据解析
     *
     * @param employeeData2
     */
    private void analysis_employeeData(String employeeData2) {
        JSONObject objs;
        try {
            objs = new JSONObject(employeeData2.toString());
            if (objs.has("success")) {
                if (objs.getBoolean("success")) {
                    if (objs.has("data")) {
                        JSONArray arr = objs.getJSONArray("data");
                        final int length = arr.length();
                        if (length > 0) {

                            for (int i = 0; i < length; i++) {
                                String userid = arr.getJSONObject(i).getString("USER_ID");
                                List<BD_ORGANIZE_EMPLOYEE> beans = NovaApplication.fdbmanger
                                        .findAllByWhere(BD_ORGANIZE_EMPLOYEE.class, "USER_ID='" + userid + "'");
                                if (beans.size() > 0) {
                                    NovaApplication.fdbmanger.deleteByWhere(BD_ORGANIZE_EMPLOYEE.class,
                                            "USER_ID='" + userid + "'");
                                }
                            }
                            for (int i = 0; i < length; i++) {
                                JSONObject obj = arr.getJSONObject(i);
                                BD_ORGANIZE_EMPLOYEE employee = new BD_ORGANIZE_EMPLOYEE();
                                employee.setBIRTHDAY(obj.getString("BIRTHDAY"));
                                employee.setBUSINESS(obj.getString("BUSINESS"));
                                employee.setBUSINESS_TEXT(obj.getString("BUSINESS_TEXT"));
                                employee.setCARD_NUM(obj.getString("CARD_NUM"));
                                employee.setDEGREE(obj.getString("DEGREE"));
                                employee.setDEPARTID(obj.getString("DEPARTID"));
                                employee.setEDUCATION(obj.getString("EDUCATION"));
                                employee.setGBCODE(obj.getString("GBCODE"));
                                employee.setGRADUATE_DATE(obj.getString("GRADUATE_DATE"));
                                employee.setHOME_ADDR(obj.getString("HOME_ADDR"));
                                employee.setHOME_TEL(obj.getString("HOME_TEL"));
                                employee.setHOME_ZIP(obj.getString("HOME_ZIP"));
                                employee.setIDCARD(obj.getString("IDCARD"));
                                employee.setINPUT_CODE(obj.getString("INPUT_CODE"));
                                employee.setINVALID(obj.getString("INVALID"));
                                employee.setISADMIN(obj.getString("ISADMIN"));
                                employee.setMAIL(obj.getString("MAIL"));
                                employee.setMARRIAGE(obj.getString("MARRIAGE"));
                                employee.setMOBILE(obj.getString("MOBILE"));
                                employee.setNAME(obj.getString("NAME"));
                                employee.setNATIONCODE(obj.getString("NATIONCODE"));
                                employee.setOFFICE_FAX(obj.getString("OFFICE_FAX"));
                                employee.setOFFICE_TEL(obj.getString("OFFICE_TEL"));
                                employee.setORG_WORK_DATE(obj.getString("ORG_WORK_DATE"));
                                employee.setORGANCODE(obj.getString("ORGANCODE"));
                                employee.setPARTY(obj.getString("PARTY"));
                                employee.setPASSWORD(obj.getString("PASSWORD"));
                                employee.setRES1(obj.getString("RES1"));
                                employee.setRES2(obj.getString("RES2"));
                                employee.setSEX(obj.getString("SEX"));
                                employee.setSPECIALITY_TEXT(obj.getString("SPECIALITY_TEXT"));
                                employee.setSTART_WORK_DATE(obj.getString("START_WORK_DATE"));
                                employee.setTECHNICAL(obj.getString("TECHNICAL"));
                                employee.setTECHNICAL_TEXT(obj.getString("TECHNICAL_TEXT"));
                                employee.setTYPE(obj.getString("TYPE"));
                                employee.setUNIVERSITY(obj.getString("UNIVERSITY"));
                                employee.setUSER_ID(obj.getString("USER_ID"));
                                employee.setUSER_NAME(obj.getString("USER_NAME"));
                                employee.setWORK(obj.getString("WORK"));
                                employee.setWORK_CARD_ID(obj.getString("WORK_CARD_ID"));
                                NovaApplication.fdbmanger.save(employee);
                                employeeCount++;
                                runOnUiThread(new Runnable() {
                                    public void run() {

                                        startRotate(iv_3_2);
                                        tv_3_2.setVisibility(View.VISIBLE);

                                        iv_3_1.setVisibility(View.GONE);
                                        tv_3_1.setVisibility(View.GONE);

                                        iv_3_3.setVisibility(View.GONE);
                                        tv_3_3.setVisibility(View.GONE);
                                    }

                                });
                                pro = 100 * employeeCount / length;
                                Message msg = new Message();
                                msg.what = MSG3_1;
                                mHandler.sendMessage(msg);
                                SystemClock.sleep(100);
                            }
                        }
                    }
                } else {
                    Message msg = new Message();
                    msg.what = MSG3_2;
                    mHandler.sendMessage(msg);

                }
            }
        } catch (Exception e) {
            Message msg = new Message();
            msg.what = MSG3_2;
            mHandler.sendMessage(msg);
        } finally {
            bt_download.setClickable(true);
        }
    }

    RotateAnimation rotate = new RotateAnimation(0f, 360f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF,
            0.5f);

    /**
     * 开始旋转动画
     *
     * @param iv
     */
    private void startRotate(ImageView iv) {
        LinearInterpolator lin = new LinearInterpolator();
        rotate.setInterpolator(lin);
        rotate.setDuration(1500);
        rotate.setRepeatCount(5);
        rotate.setFillAfter(false);
        iv.setVisibility(View.VISIBLE);
        iv.setAnimation(rotate);
        rotate.startNow();
    }

    /**
     * 结束旋转动画并隐藏图片
     *
     * @param iv
     */
    private void stopRotate(ImageView iv) {
        rotate.cancel();
        iv.clearAnimation();
        iv.setVisibility(View.GONE);
    }
}
